/*
 * @Author: Zeratul
 * @Date: 2020-08-19 19:52:05
 * @LastEditTime: 2020-08-24 04:32:51
 * @FilePath: \sz-h5-2003-react-mobile\zhangminhui\eleme-react\eleme-apiServer\app.js
 */
var createError = require("http-errors");
var express = require("express");
const cors = require("cors");
const md5 = require("md5");
const moment = require("moment");
const token = require("jsonwebtoken");
const session = require("express-session");
("express-session");
const { connection, spell, SetID } = require("./config");
const mysql = require("mysql");
const bodyParser = require("body-parser");
const multer = require("multer");
const { userModel } = require("./model/dataModels");
var app = express();

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "./uploads");
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname);
  },
});

var upload = multer({
  storage: storage,
});
app.use(upload.single("file"));
//设置跨域
app.use(cors());
//设置body-parser
app.use(
  bodyParser.urlencoded({
    extended: true,
  })
);
//建立数据库连接
var myCon = mysql.createConnection(connection);
myCon.connect();
//设置session
app.use(
  session({
    secret: "Avada Kedavra",
    resave: false,
    saveUninitialized: true,
    cookie: {
      maxAge: 1000 * 60 * 60,
    },
  })
);

//#region 用户
/**
 * 用户-注册
 *@param {String} userName
 *@param {String} password
 *@param {String} telephone
 */
app.post("/api/user/regist", function (req, res) {
  let body = req.body;
  let tablename = "users";
  let userID = SetID(tablename);
  userModel["userID"] = userID;
  for (let key in body) {
    if (key == "password") {
      body["password"] = md5(spell + body["password"] + spell);
    }
    if (body[key]) {
      userModel[key] = body[key];
    }
  }
  let sqlQuery = "select * from users where telephone=" + userModel.telephone;
  console.log(sqlQuery);
  myCon.query(sqlQuery, function (queryerror, queryresults, queryfields) {
    if (!queryerror) {
      if (queryresults.length > 0) {
        res.send({ code: 204, content: "用户名已存在" });
      } else {
        console.log("用户不存在");
        let arrKeys = [];
        let arrValues = [];
        for (let key in userModel) {
          if (userModel[key]) {
            arrKeys.push(key);
            arrValues.push("'" + userModel[key] + "'");
          }
        }
        let sql =
          "insert into users(" +
          arrKeys.toString() +
          ") values (" +
          arrValues.toString() +
          ")";
        console.log(sql);
        myCon.query(sql, function (error, results, fields) {
          if (!error) {
            res.send({ code: 200, content: "success", results });
          } else {
            res.send({ code: 500, content: "error:", error });
          }
        });
      }
    }
  });
});

/**
 * 用户-登陆
 * @param {String} telephone
 * @param {string} password
 */
app.post("/api/user/login", function (req, res) {
  let body = req.body;
  console.log(body);
  for (let key in body) {
    if (body[key]) {
      userModel[key] = body[key];
    }
  }
  userModel["password"] = md5(spell + userModel["password"] + spell);
  let sql =
    "select * from users where telephone='" +
    userModel.telephone +
    "' and password='" +
    userModel.password +
    "'";
  console.log(sql);
  myCon.query(sql, function (error, results, fields) {
    if (!error) {
      if (results.length > 0) {
        res.send({ code: 200, content: "success", results });
      } else {
        res.send({ code: 404, content: "用户名或密码错误" });
      }
    } else {
      res.send({ code: 500, content: "error:", results });
      return;
    }
  });
});
/**
 * 用户-修改用户信息
 * @param {String} userID
 * @param {Object} userModel
 */
app.post("/api/user/modifyUserInfo", function (req, res) {
  let body = req.body;
  for (let key in body) {
    userModel[key] = body[key];
  }
  let arrUpdate=[];
  for(let key in userModel){
    if(userModel[key]){
      arrUpdate.push(key+"='"+userModel[key]+"'");
    }
  }
  let sql="update users set "+arrUpdate.toString() +"where userID="+userModel.userID;
  myCon.query(sql,function(error,results,fields){
  if(!error){
      res.send({code:200,content:'success',results});
  }else{
      res.send({code:500,content:'error:',results});
      return;
      }
  })
});

/**
 * 主页-搜索
 * @param {String} inputValue
 */
app.post("/api/index/searhInfo", function (req, res) {
  let body = req.body;
  let sql =
    "SELECT productName as result FROM products where productName like '%" +
    body.inputValue +
    "%' union select sortOName as result from sort_one where sortOName like '%" +
    body.inputValue +
    "%' union select sortTName as result from sort_two where sortTName like '%" +
    body.inputValue +
    "%' union select shopTypeOName as result from shop_type_one where shopTypeOName like '%" +
    body.inputValue +
    "%' union select shopTypeTName as result from shop_type_two where shopTypeTName like '%" +
    body.inputValue +
    "%'";
  console.log(sql);
  myCon.query(sql, function (error, results, fields) {
    if (!error) {
      res.send({ code: 200, content: "success", results });
    } else {
      res.send({ code: 500, content: "error:", results });
      return;
    }
  });
});
//#endregion

module.exports = app;
